package com.sanley.coronavirus.common.security;

import com.alibaba.fastjson2.JSON;
import com.sanley.coronavirus.common.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: ming
 * @create: 2022-10-14 21:12
 * @program: coronavirus
 */
@Slf4j
@Service("authenticationEntryPointImpl")
class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response,
                         AuthenticationException e) throws IOException {
        log.error("Spring Securtiy异常", e.getMessage());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        PrintWriter out = response.getWriter();
        out.print(JSON.toJSONString(CommonResult.unauthorized("未登录，请先登录！")));
    }
}
